#/bin/bash
#mysql源码包安装脚本，运行之前需要传压缩包到脚本同级目录
echo "请检查脚本是否具有执行权限"
echo "请检查相应版本的安装包是否已经上传到服务器"
mysql_setup=5.7.30
user=mysql
group=mysql
mysql_path=/home
port=3306
OS=`cat /etc/redhat-release|sed -r 's/.* ([0-9]+)\..*/\1/'`
#检查目录中是否有对应安装包
if test -n "`ls -a | grep ${mysql_setup} `"
then
	echo "您已经成功上传了安装包到同级的目录"
else
   exit 0
fi

#创建mysql对应的用户组和用户
groupadd mysql
useradd -M -s /sbin/nologin mysql -g mysql

#解压mysql文件夹并传到相应的安装目录
tar xvfz mysql-${mysql_setup}-linux-glibc2.12-x86_64.tar.gz
mv mysql-${mysql_setup}-linux-glibc2.12-x86_64 /usr/local/mysql

#创建mysql数据存放及日志目录
mkdir -p ${mysql_path}/mysql 
mkdir -p ${mysql_path}/mysql/binlog
mkdir -p ${mysql_path}/mysql/log 
mkdir -p ${mysql_path}/mysql/data 
mkdir -p ${mysql_path}/mysql/redo 
touch  ${mysql_path}/mysql/log/mysqld.log

#修改mysql目录的权限，重要，不然会初始化失败
chown -R ${user}:${group} /usr/local/mysql/ 
chown -R ${user}:${group} ${mysql_path}/mysql
chmod -R 775 ${mysql_path}/mysql
chmod -R 775 /usr/local/mysql

#修改配置文件
cat > /etc/my.cnf <<EOF
[client] 
port = ${port} 
socket = ${mysql_path}/mysql/mysql.sock 
[mysqld] 
port = ${port} 
user = ${user} 
socket = ${mysql_path}/mysql/mysql.sock 
basedir = /usr/local/mysql 
datadir = ${mysql_path}/mysql/data 
#bin-log log-bin=${mysql_path}/mysql/binlog/mysql-bin 
max_binlog_size=512M 
expire_logs_days = 30 
server_id=2433306 
# character-set utf8 
character-set-server = utf8 
#innodb default_storage_engine = innodb 
innodb_data_home_dir=${mysql_path}/mysql/data 
innodb_data_file_path=ibdata1:10M:autoextend 
innodb_log_group_home_dir=${mysql_path}/mysql/redo 
innodb_log_file_size=512M 
innodb_log_files_in_group=3 
innodb_buffer_pool_size = 20G 
innodb_buffer_pool_instances = 16 
innodb_log_buffer_size = 16777216 
innodb_print_all_deadlocks = 1 
innodb_sort_buffer_size = 67108864 
innodb_open_files = 4096
innodb_print_all_deadlocks = 1 
innodb_sort_buffer_size = 67108864 
innodb_open_files = 4096 
#error-log log-error=${mysql_path}/mysql/log/mysqld.log
#connection max_connections = 3000 
max_allowed_packet = 16777216 
#table cache table_open_cache = 4096 
table_definition_cache = 4096 
table_open_cache_instances = 128
EOF

#初始化数据库
cd /usr/local/mysql/
./bin/mysqld --initialize --user=${user} --basedir=/usr/local/mysql --datadir=${mysql_path}/mysql/data

#配置启动文件
cd /usr/local/mysql
cp support-files/mysql.server /etc/init.d/mysqld
chmod 755 /etc/init.d/mysqld
chkconfig --add mysqld
chkconfig --list mysqld

#启动mysql数据库
if [ "$OS" == "7" ];then
	systemctl start mysqld
else
	service mysqld start
fi

#将mysql将入到环境变量里面
echo ""
cat >>/etc/profile <<EOF
MYSQL_HOME=/usr/local/mysql
export PATH=\$PATH:\$MYSQL_HOME/bin
EOF

#刷新环境变量
source /etc/profile

#检测mysql是否安装成功
mysqlstatu=`ps -ef |grep mysql |grep -v "grep"`
if [ -z "${mysqlstatu}" ];then
	echo "mysql 安装失败，请查看日志检查失败原因"
else
	echo "您已经成功安装了mysql"
fi


